package com.ruoyi.app.controller;

import com.github.pagehelper.PageHelper;
import com.ruoyi.app.vo.ProductCategoryVo;
import com.ruoyi.business.constant.JtUserConstants;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.service.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品信息
 * @Author Alan Zhang
 * @Date 2025/3/15 13:21
 */
@RestController
@RequestMapping("/api/product")
public class ProductApiController extends BaseApiController {
    @Autowired
    private IJtProductService jtProductService;
    @Autowired
    private IJtProductPublishService jtProductPublishService;
    @Autowired
    private IJtProductCategoryService jtProductCategoryService;
    @Autowired
    private IJtProductTraceabilityService jtProductTraceabilityService;
    @Autowired
    private IJtCountryCodeService jtCountryCodeService;
    @Autowired
    private ISysConfigService configService;

    //========== 商品详情 =========
    @PostMapping("/detail")
    public AjaxResult detail(Long productId)
    {
        JtProductPublish jtProduct = jtProductPublishService.selectJtProductPublishByProductId(productId);
        if(StringUtils.isNotEmpty(jtProduct.getDetails())){
            String details = replaceImgSrc(jtProduct.getDetails());
            jtProduct.setDetails(details);
        }

        return AjaxResult.success("detail success", jtProduct);
    }

    private String replaceImgSrc(String htmlContent){
        String baseUrl = configService.selectConfigByKey("sys.domain.name");
        if(StringUtils.isEmpty(baseUrl)){
            return htmlContent;
        }
        Document doc = Jsoup.parseBodyFragment(htmlContent);
        Elements anchors = doc.select("img");

        for(Element anchor : anchors){
            // 创建新的img元素
            Element newImg = anchor.clone(); // 克隆原始元素，避免丢失属性
            String srcVal = newImg.attr("src");
            if(StringUtils.isNotEmpty(srcVal)) {
                newImg.attr("src", baseUrl + srcVal);

                anchor.replaceWith(newImg);
            }
        }
        return doc.body().html();
    }

    //========== 商品分类 =========
    @PostMapping("/category")
    public AjaxResult category(String lang)
    {
        //有效 商品分类
        JtProductCategory param = new JtProductCategory();
        param.setStatus(0);
        List<JtProductCategory> productCategoryList = jtProductCategoryService.selectJtProductCategoryList(param);

        List<ProductCategoryVo> categoryVoList = new ArrayList<>();
        if(JtUserConstants.ZH_CN.equals(lang)) {

            for(JtProductCategory item: productCategoryList){
                ProductCategoryVo productCategoryVo = new ProductCategoryVo();
                productCategoryVo.setCategoryId(item.getCategoryId());
                productCategoryVo.setCategoryName(item.getCategoryNameZh());
                categoryVoList.add(productCategoryVo);
            }
        } else if(JtUserConstants.EN_US.equals(lang)){
            for(JtProductCategory item: productCategoryList){
                ProductCategoryVo productCategoryVo = new ProductCategoryVo();
                productCategoryVo.setCategoryId(item.getCategoryId());
                productCategoryVo.setCategoryName(item.getCategoryNameEn());
                categoryVoList.add(productCategoryVo);
            }
        } else if(JtUserConstants.AR_SA.equals(lang)){
            for(JtProductCategory item: productCategoryList){
                ProductCategoryVo productCategoryVo = new ProductCategoryVo();
                productCategoryVo.setCategoryId(item.getCategoryId());
                productCategoryVo.setCategoryName(item.getCategoryNameAr());
                categoryVoList.add(productCategoryVo);
            }
        } else {
            for(JtProductCategory item: productCategoryList){
                ProductCategoryVo productCategoryVo = new ProductCategoryVo();
                productCategoryVo.setCategoryId(item.getCategoryId());
                productCategoryVo.setCategoryName(item.getCategoryNameZh());
                categoryVoList.add(productCategoryVo);
            }
        }
        return AjaxResult.success("success", productCategoryList);
    }



    //========== 商品信息列表 =========
    @PostMapping("/list")
    public AjaxResult list(Long categoryId, int pageNum, int pageSize)
    {
        JtAppUser jtAppUser = getTokenAppUser();

        //用户所在国家
        JtCountryCode paramCountry = new JtCountryCode();
        paramCountry.setCountryCode(jtAppUser.getCountryCode());
        List<JtCountryCode> countryCodeList = jtCountryCodeService.selectJtCountryCodeList(paramCountry);
        JtCountryCode countryCodeDb = countryCodeList.get(0);

        JtProductPublish paramProduct = new JtProductPublish();
        paramProduct.setStatus(1);//在售的商品
        paramProduct.setCategoryId(categoryId);

        //发布地区
        paramProduct.setPublishCountryCode(countryCodeDb.getCountryCode().toString());
        PageUtils.startPage();
        //排序字段
        PageHelper.orderBy("create_time desc");

        List<JtProductPublish> productList = jtProductPublishService.selectJtProductPublishList(paramProduct);
        //过渡代码
        for(JtProductPublish item: productList){
            if(StringUtils.isNotEmpty(item.getDetails())){
                String details = replaceImgSrc(item.getDetails());
                item.setDetails(details);
            }
        }
        TableDataInfo tableDataInfo = getDataTable(productList);
        return AjaxResult.success("success", tableDataInfo);
    }

    //========== 商品信息搜索列表 =========
    @PostMapping("/search/list")
    public AjaxResult searchList(String productName)
    {
        JtAppUser jtAppUser = getTokenAppUser();

        if(StringUtils.isEmpty(productName)){
           return AjaxResult.error("请输入关键字进行搜索");
        }
        //用户所在国家
        JtCountryCode paramCountry = new JtCountryCode();
        paramCountry.setCountryCode(jtAppUser.getCountryCode());
        List<JtCountryCode> countryCodeList = jtCountryCodeService.selectJtCountryCodeList(paramCountry);
        JtCountryCode countryCodeDb = countryCodeList.get(0);

        JtProductPublish paramProduct = new JtProductPublish();
        paramProduct.setStatus(1);//在售的商品
        paramProduct.setProductTitle(productName);
        //发布地区
        paramProduct.setPublishRegion(countryCodeDb.getCountryRegion());

        PageUtils.startPage();
        //排序字段
        PageHelper.orderBy("create_time desc");
        List<JtProductPublish> productList = jtProductPublishService.selectJtProductPublishList(paramProduct);

        TableDataInfo tableDataInfo = getDataTable(productList);
        //在售的商品
        return AjaxResult.success("success",tableDataInfo);
    }


    //========== 商品溯源 =========
    @PostMapping("/traceability")
    public AjaxResult traceability(String productCode)
    {
        if(StringUtils.isEmpty(productCode)){
            return AjaxResult.error("商品溯源码不能为空");
        }
        JtProductTraceability param = new JtProductTraceability();
        param.setTraceabilityCode(productCode);
        List<JtProductTraceability> jtProductTraceabilityList = jtProductTraceabilityService.selectJtProductTraceabilityList(param);
        if(jtProductTraceabilityList.size() > 0){
            return AjaxResult.success("traceability success", jtProductTraceabilityList.get(0));
        } else {
            return AjaxResult.error("该产品溯源信息不存在！");
        }

    }
}
